import { Component, Inject, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { RestService } from '../../services/rest.service';
import { DataService } from './../../services/data.service';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { GridOptions } from 'ag-grid/main';
import { Subscription } from 'rxjs/Rx';

import * as _ from 'lodash';

@Component({
  selector: 'app-traininfo-dialog',
  templateUrl: './traininfo-dialog.component.html',
  styleUrls: ['./traininfo-dialog.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class TraininfoDialogComponent implements OnDestroy {
  contentHeight = 'auto';
  train: string;

  subscription: Subscription;
  gridOptions: GridOptions;
  columnDefs: any[];
  rowData: any[];

  constructor(public dialogRef: MatDialogRef<TraininfoDialogComponent>,
              private restService: RestService,
              private dataService: DataService,
              @Inject(MAT_DIALOG_DATA) private dialogData: any) {
    this.train = this.dialogData.event.train;
    this.gridOptions = this.restService.getGeneralGridOptions();
    this.gridOptions.overlayNoRowsTemplate = '<span class="csf-overlay">无故障数据</span>';
    this.columnDefs = this.buildColumnDefs();
    this.fillData(this.dialogData.event);

    this.subscription = this.dataService.data$.subscribe(event => {
      if (_.isString(event)) {
        return;
      }

      this.fillData(event[0]);
    });
  }

  buildColumnDefs() {
    const columnDefs = [];
    columnDefs.push({
      headerName: '列车号',
      field: 'train',
      minWidth: 70
    }, {
      headerName: '更新时间',
      field: 'time',
      minWidth: 160
    }, {
      headerName: '故障描述',
      field: 'name',
      minWidth: 160
    });

    return columnDefs;
  }

  fillData(data) {
    const faults = this.restService.getFaults(data);
    if (_.isEmpty(faults)) {
      this.rowData = [];
      return;
    }

    const updateTime = this.restService.getUpdatedTime(data);
    this.rowData = [];
    faults.forEach(fault => {
      this.rowData.push({
        train: '001',
        time: updateTime,
        name: fault
      });
    });
  }

  /**
   * Grid API was included in params.
   */
  onGridReady(params) {
    params.api.sizeColumnsToFit();
  }

  selectAllRows() {
    this.gridOptions.api.selectAll();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
